package com.azarias.component;

import lombok.extern.slf4j.Slf4j;

/**
 * @description: 所有已注册服务的心跳计数器,单例
 * @author: Azarias_Jx
 * @date: 2022/1/4 11:19
 */
@Slf4j
public class HeartbeatTimesCounter {

    private static HeartbeatTimesCounter instance = new HeartbeatTimesCounter();

    public static HeartbeatTimesCounter getInstance(){
        return instance;
    }

    //后台线程清理每分钟心跳总次数
    private Daemon daemon ;

    private HeartbeatTimesCounter(){
        this.daemon = new Daemon();
        this.daemon.setDaemon(true);
        this.daemon.start();
    }
    /**
     * 最近一分钟的心跳次数
     */
    private long latestMinuteHeartbeatRate = 0L;

    /**
     * 最近一分钟的时间戳
     */
    private long latestMinuteTimestamp = System.currentTimeMillis();

    //获得最近一分钟的心跳次数
    public long getLatestMinuteHeartbeatRate(){
        return latestMinuteHeartbeatRate;
    }
    /**
     * 增加一次最近一分钟的心跳次数
     */
    public void increment() {
        synchronized (HeartbeatTimesCounter.class) {
            latestMinuteHeartbeatRate++;
        }
    }
    //后台线程，每一分钟清空一次心跳次数
    private class Daemon extends Thread{
        @Override
        public void run() {
            while (true){
                try{
                    synchronized (HeartbeatTimesCounter.class){
                        long currentTimeMillis = System.currentTimeMillis();
                        if(currentTimeMillis-latestMinuteTimestamp>=60*1000){
                            latestMinuteTimestamp = System.currentTimeMillis();
                            latestMinuteHeartbeatRate = 0L;
                        }
                    }
                    Thread.sleep(1000);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }


}
